package cn.wonderland.user.service.impl;

import cn.wonderland.base.cons.PhoneRegisterCon;
import cn.wonderland.base.cons.WechatCon;
import cn.wonderland.base.jwt.JwtUtils;
import cn.wonderland.base.jwt.RsaUtils;
import cn.wonderland.base.jwt.UserInfo;
import cn.wonderland.base.util.AjaxResult;
import cn.wonderland.base.util.BussinessException;
import cn.wonderland.base.util.HttpUtil;
import cn.wonderland.base.util.MD5Utils;
import cn.wonderland.org.domain.Employee;
import cn.wonderland.org.domain.Shop;
import cn.wonderland.org.mapper.EmployeeMapper;
import cn.wonderland.org.mapper.ShopMapper;
import cn.wonderland.user.service.LoginService;
import cn.wonderland.system.domain.Menu;
import cn.wonderland.system.mapper.MenuMapper;
import cn.wonderland.system.mapper.PermissionMapper;
import cn.wonderland.user.domain.Logininfo;
import cn.wonderland.user.domain.User;
import cn.wonderland.user.domain.Wxuser;
import cn.wonderland.user.dto.AccountLoginDto;
import cn.wonderland.user.dto.BinderDto;
import cn.wonderland.user.dto.WechatDto;
import cn.wonderland.user.mapper.LogininfoMapper;
import cn.wonderland.user.mapper.UserMapper;
import cn.wonderland.user.mapper.WxuserMapper;
import com.alibaba.fastjson.JSONObject;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.security.PrivateKey;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class LoginServiceImpl implements LoginService {
    @Autowired
    private LogininfoMapper logininfoMapper;
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private WxuserMapper wxuserMapper;
    @Autowired
    private UserMapper userMapper;

    @Autowired
    private PermissionMapper permissionMapper;
    @Autowired
    private MenuMapper menuMapper;
    @Value("${jwt.pri}")
    private String pri;

    @Autowired
    private EmployeeMapper employeeMapper;
    @Autowired
    private ShopMapper shopMapper;

    /**
     * 登录实现
     * @param dto
     * @return
     */
    @Override
    public AjaxResult account(AccountLoginDto dto) {
        // 1.参数校验
        // 2.根据账号(账号、手机号、邮箱号)查询用户是否存在
       Logininfo logininfo = logininfoMapper.findByAccount(dto);
       if (logininfo == null){
           throw new BussinessException("账号或密码错误，请重试！");
       }
        // 3.判断密码是否正确
        String dbPwd = logininfo.getPassword();
        String webPwd = MD5Utils.encrypByMd5(logininfo.getSalt() + dto.getPassword());
        if (!dbPwd.equals(webPwd)){
            throw new BussinessException("账号或密码错误，请重试！");
        }
        // 4.后端生成uuid作为key == token
        Map<String, Object> result = getMap(logininfo);
        return AjaxResult.me().success(result);
    }

    // 微信扫码登录
    @Override
    public AjaxResult wechat(WechatDto dto) {
        // 1.参数校验
        // 2.通过code进行二部曲获取token和openid
        String jsonStr = HttpUtil.httpGet(String.format(WechatCon.SECOND_INTER, WechatCon.APPID, WechatCon.SECRET, dto.getCode()));
        // 2.1 json中取出token 和openid
        JSONObject jsonObject = JSONObject.parseObject(jsonStr);
        String access_token = jsonObject.getString("access_token");
        String openid = jsonObject.getString("openid");
        // 3.通过openid查询wxuser是否有值
        Wxuser wxuser = wxuserMapper.findByOpenid(openid);
        if (null != wxuser && null != wxuser.getUserId()) { // 判断wxuser是否存在userid
            // 如果存在就表示用户已经通过其他方式登录过，跳转到登录页
            // 根据wxuser中的userid查询logininfo信息
            Logininfo logininfo = logininfoMapper.findByUserId(wxuser.getUserId());
            // 4.后端生成uuid作为key == token
            Map<String, Object> result = getMap(logininfo);
            return AjaxResult.me().success(result);

        }
        // 4.没有数据就跳转到绑定页面 "?accessToken="+accessToken+"&openId="+openId
        StringBuilder sb = new StringBuilder();
        sb.append("?accessToken=")
                .append(access_token)
                .append("&openId=")
                .append(openid);
        return AjaxResult.me().fail("nobinder").setResultObj(sb.toString());
    }

    // 账号绑定
    @Override
    public AjaxResult binder(BinderDto dto) {
        // 1.参数校验
        // 2.判断手机验证码是否正确
        String redisSmsCode = (String) redisTemplate.opsForValue().get(String.format(PhoneRegisterCon.BINDER_REDIS_KEY, dto.getPhone()));
        if (StringUtils.isBlank(redisSmsCode) || !redisSmsCode.equals(dto.getVerifyCode())) {
            throw new BussinessException("验证码错误！");
        }
        // 3.进行第三部曲
        String jsonStr = HttpUtil.httpGet(String.format(WechatCon.THIRD_INTER, dto.getAccessToken(), dto.getOpenId()));
        // 3.1 转换jsonStr格式
        Wxuser wxuser = JSONObject.parseObject(jsonStr, Wxuser.class);
        // 4.判断user里面是否有数据 根据手机号查询user表
        User user = userMapper.findByPhone(dto.getPhone());
        Logininfo logininfo = new Logininfo();
        if (null == user) {
            // 没有数据 保存三张表 logininfo user wxuser
            user = dto.getUser();
            BeanUtils.copyProperties(user, logininfo);
            logininfo.setType(1);
            logininfo.setDisable(1);
            // 先去添加logininfo对象
            logininfoMapper.add(logininfo);
            user.setLogininfoId(logininfo.getId());
            userMapper.add(user);
        }
        // 添加wxuser
        wxuser.setUserId(user.getId());
        wxuserMapper.add(wxuser);
        Map<String, Object> result = getMap(logininfo);
        return AjaxResult.me().success(result);
    }

    /**
     * 抽取公共方法
     * @param logininfo
     * @return
     */
//    private Map<String, Object> getMap(Logininfo logininfo) {
//        // 4.后端生成uuid作为key == token
//        String token = UUID.randomUUID().toString();
//        // 5.存储数据到redis中  key：token  value：logininfo
//        redisTemplate.opsForValue().set(token, logininfo);
//        // 6.清空敏感信息
//        logininfo.setPassword(null);
//        logininfo.setPhone(null);
//        // 7.将token和logininfo数据返回前端
//        Map<String, Object> result = new HashMap<>();
//        result.put("token", token);
//        result.put("logininfo", logininfo);
//        return result;
//    }

    /**
     * jwt改造
     * @param logininfo
     * @return
     */
    private Map<String, Object> getMap(Logininfo logininfo) {
        // 7.将token和logininfo数据返回前端
        Map<String, Object> result = new HashMap<>();
        // 1 获取token
        PrivateKey privateKey = RsaUtils.getPrivateKey(JwtUtils.class.getClassLoader().getResource(pri).getFile());
        UserInfo userInfo = new UserInfo();
        userInfo.setLogininfo(logininfo);

        if (logininfo.getType() == 0) { // 判断是否是后台人员，不然就不用查权限
            // 查询员工的按钮权限
            List<String> snList = permissionMapper.findByLogininfoId(logininfo.getId());
            // 查询员工的菜单权限
            List<Menu> menus =  menuMapper.findByLogininfoId(logininfo.getId());
            // 赋值
            userInfo.setPermissions(snList);
            userInfo.setMenus(menus);
            // 返回给前端
            result.put("permissions", snList);
            result.put("menus", menus);
            // 后台用户 有可能是店铺员工
            Employee employee = employeeMapper.findByLogininfoId(logininfo.getId());
            if (null != employee && null != employee.getShopId()) {
                Shop shop = shopMapper.findById(employee.getShopId());
                userInfo.setShop(shop);
            }
        }
        String token = JwtUtils.generateTokenExpireInMinutes(userInfo, privateKey, 3000);
        // 6.清空敏感信息
        logininfo.setPassword(null);
        logininfo.setPhone(null);
        // 返回给前端
        result.put("token", token);
        result.put("logininfo", logininfo);
        return result;
    }
}
